package org.vectrics.common.html;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeSet;
import org.vectrics.SystemException;
import org.vectrics.common.util.FileUtil;
import org.vectrics.domain.Domain;
import org.vectrics.domain.HtmlCssEntry;
import org.vectrics.domain.HtmlCssEntryComparator;
import org.vectrics.domain.HtmlFormType;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.VectricsTagSupport;


public class StyleSheetSectionTagCopy extends VectricsTagSupport {
	private String form = null;
	
	public StyleSheetSectionTagCopy() {
		super();
	}

	protected String makeStartTag() {
		Domain domain = ThreadProperties.getDomain();
		if (domain == null)
			throw new SystemException("Data Owner is null");
		
		String formCode = this.getForm();
		HtmlFormType formType = CoreServiceLocator.getSystemService().findHtmlFormType(formCode);
		
		String cachedHtml = findCachedHtml(domain, formType);
		if (cachedHtml == null) {
			log.debug("Could not find cached style sheet - looking up entries");
			StringBuffer html = new StringBuffer();
			html.append("\r\n<style><!-- ");
			Collection cssEntries = CoreServiceLocator.getSystemService()
				.findCssEntries(domain, formType);
			
			while ((cssEntries.size() == 0) && (domain.getParent() != null)) {
				domain = domain.getParent();
				cssEntries = CoreServiceLocator.getSystemService()
					.findCssEntries(domain, formType);
			}
			
			TreeSet sortedEntries = new TreeSet(new HtmlCssEntryComparator());
			sortedEntries.addAll(cssEntries);
			
			Iterator iter = sortedEntries.iterator();
			HtmlCssEntry previousEntry = null;
			Collection propertyEntries = new HashSet();
			boolean done = false;
			while (!done) {
				HtmlCssEntry cssEntry = null;
				if (iter.hasNext()) {
					cssEntry = (HtmlCssEntry)iter.next();
					log.info("stylesheet - adding css entry: " + cssEntry);
				} else {
					done = true;
					if (propertyEntries.size() > 0) {
						appendClassProperties(html, propertyEntries);
					}
				}
				
				if (previousEntry == null) {
					if (cssEntry == null) {
					} else {
						log.info("stylesheet - adding css entry to set: " + cssEntry);
						propertyEntries.add(cssEntry);
					}	
				} else {
					if (cssEntry == null) {
						appendClassProperties(html, propertyEntries);
						done = true;
					} else {
						if ( cssEntry.getClassName().equals(previousEntry.getClassName()))
							// cssEntry.getParameter().equals(previousEntry.getParameter())) 
					    //  )
						{
							propertyEntries.add(cssEntry);
						} else {
							appendClassProperties(html, propertyEntries);
							propertyEntries.add(cssEntry);
						}
					}
					
				}
				previousEntry = cssEntry;
				/*
					line = cssEntry.getClassName() + "{" + cssEntry.getValue() + "}\r\n";
					try {
						html.append(line);
					} catch (Exception ex) {
						throw new SystemException("IOException writing stream", ex);
					}
				*/
			}
			
			html.append("--></style>\r\n");
			cachedHtml = html.toString();
			saveHtmlToCache(cachedHtml, domain, formType);
		}
		return cachedHtml;
	}

	
	public void appendClassProperties(StringBuffer html, Collection propertyEntries) {
		Iterator iter = propertyEntries.iterator();
		if (iter.hasNext()) {
			boolean first = true;
			while (iter.hasNext()) {
				HtmlCssEntry entry = (HtmlCssEntry)iter.next();
				if (first) {
					html.append(entry.getClassName() + "{");
				}
				html.append(entry.getParameter() + ": " + entry.getValue());
				if (iter.hasNext()) {
					html.append("; ");
				}
				first = false;
			}
			html.append("}\r\n");
		}
		propertyEntries.clear();
	}
	
	public void saveHtmlToCache(String cachedHtml, Domain domain, HtmlFormType formType) {
		String fileName = formType.getCssFileName(domain);
		FileUtil.saveContentToFile(fileName, cachedHtml);
	}
	
	public String findCachedHtml(Domain domain, HtmlFormType formType) {
		URL url = null;
		URLConnection urlConnection = null;
		String cachedHtml = null;
		String fileName = formType.getCssFileName(domain);
		InputStream input =null;
		try {
			url = new URL(fileName);
			urlConnection = url.openConnection();
			input = urlConnection.getInputStream();
		} catch (MalformedURLException ex) {
			log.error("Mal Formada la URL: " + fileName, ex);
			throw new SystemException("Mal Formada la URL: " + fileName, ex);
		} catch (IOException ex) {
			log.error("Exception opening URL: " + fileName, ex);
			throw new SystemException("Exception opening file: " + fileName, ex);
		}
		StringBuffer str = new StringBuffer();
		try {
            int c;
            do {
                c = input.read();
                if (c != -1)
                    str.append((char)c);
            } while (c != -1);
            input.close();
        }
        catch (Exception ex) {
            str.append(ex.getMessage());
            log.error("Exception loading: " + fileName, ex);
        };
		cachedHtml = str.toString();
		if (cachedHtml.trim().length() == 0) {
				cachedHtml = null;
		} 
		return(cachedHtml);
	}
	
	
	
	/**
	 * @return Returns the form.
	 */
	public String getForm() {
		return form;
	}

	/**
	 * @param form The form to set.
	 */
	public void setForm(String form) {
		this.form = form;
	}
	
	
}
